/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.engine.cmd.application;

import cn.easyplatform.i18n.I18N;
import cn.easyplatform.interceptor.AbstractCommand;
import cn.easyplatform.interceptor.CommandContext;
import cn.easyplatform.messages.request.SimpleRequestMessage;
import cn.easyplatform.messages.response.SimpleResponseMessage;
import cn.easyplatform.type.IResponseMessage;
import cn.easyplatform.utils.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

public class CreateUserCmd extends AbstractCommand<SimpleRequestMessage> {

    private final static String CMD0 = "INSERT INTO `ep_user_info`(`userId`, `name`, `password`, `type`, `validDate`, `validDays`, `loginFailedTimes`, `lastLoginTime`, `lastLogoutTime`, `ipAddress`, `salt`, `theme`, `editorTheme`, `roleId`, `state`) VALUES (?,?,?, 1, NULL, 0, 0, NULL, NULL, NULL, ?, NULL, NULL, '', 1)";

    private final static String CMD1 = "INSERT INTO `ep_user_project_info`(`userId`, `projectId`) VALUES (?,?)";

    private final static Logger log = LoggerFactory.getLogger(CreateUserCmd.class);

    public CreateUserCmd(SimpleRequestMessage req) {
        super(req);
    }

    @Override
    public IResponseMessage<?> execute(CommandContext cc) {
        if (log.isInfoEnabled())
            log.info("CreateUser {}", req.getBody());
        Map<String, String> data = (Map<String, String>) req.getBody();
        String userId = data.get("userId"), projectId = data.get("projectId"), password = data.get("password");
        Number num = (Number) cc.getEntityDao().selectObject("SELECT COUNT(*) FROM ep_user_info WHERE userId=?", userId);
        if (num.intValue() > 0)//用户已存在
            return new SimpleResponseMessage("e022", I18N.getLabel("app.user.exists", userId));
        String salt = SecurityUtils.getSalt();
        password = SecurityUtils.getSecurePassword(password, salt);
        cc.getEntityDao().update(CMD0, userId, userId, password, salt);
        cc.getEntityDao().update(CMD1, userId, projectId);
        return new SimpleResponseMessage();
    }
}
